package org.springblade.metadata.filter;


import org.apache.atlas.AtlasServiceException;
import org.springblade.metadata.service.API_V2Url;
import org.springblade.metadata.service.AtlasProxyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@Order(1)
//@Component
@WebFilter(filterName = "metaFilter", urlPatterns = { "/api/atlas/*"})
public class MetaFilter implements Filter{
    
    @Autowired
    private AtlasProxyService atlasProxyService;
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		 HttpServletRequest request = (HttpServletRequest) servletRequest;
		 log.info("request path is {}", request.getRequestURI());
		 if(request.getRequestURI().startsWith("/api/meta/api/atlas/")) {
			 
			 String uri = request.getRequestURI().replaceFirst("/api/meta/", "");
			 log.info("request path is {}", uri);
//		 uri = uri.replace("api/meta", "");
			 log.info("request method is {}" , request.getMethod());
			 PrintWriter writer = null;
			 response.setCharacterEncoding("UTF-8");
			 response.setContentType("application/json; charset=utf-8");
			 try {
				 writer = response.getWriter();
				 Map<String, Object> result = new HashMap<String, Object>();
				 result.put("data", "abc");
				 API_V2Url au = atlasProxyService.getAPI(uri,request.getMethod());
				 String[] ss = atlasProxyService.extract(au, uri);
				 try {
					 log.info("start call api : {}   {}  ",au.getApi().getPath() , au.getApi().getMethod());
					 String s= atlasProxyService.call(au.getApi(), request, ss);
					 writer.print(s);
				 } catch (AtlasServiceException e) {
					 // TODO Auto-generated catch block
					 e.printStackTrace();
					 writer.print(e.getMessage());
				 }
				 
				 
			 } finally {
				 if(writer != null){
					 writer.close();
				 }
			 }
		 }else {
			 chain.doFilter(request, response);
		 }
		 

	}

}
